/*
 * File     : PointerParameter.java
 * Created  : 22 Apr 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.call;

import static com.googlecode.dni.internal.DniTypes.POINTER_TYPE;
import static org.objectweb.asm.Opcodes.*;

import org.objectweb.asm.MethodVisitor;

import com.googlecode.dni.internal.DniTypes;
import com.googlecode.dni.type.Pointer;


/**
 * <p>
 *  Encapsulates a parameter to a native call that comes from a {@link Pointer}.
 * </p>
 *
 * @author Matthew Wilson
 */
final class PointerParameter extends Parameter
{

    {
        setNativeTypeAsPointer();
    }

    /** {@inheritDoc} */
    @Override
    int getJavaVarSlots()
    {
        return 1;
    }

    /** {@inheritDoc} */
    @Override
    void writeGetParameter( final MethodVisitor methodVisitor )
    {
        methodVisitor.visitVarInsn( ALOAD, getJavaVarIndex() );

        methodVisitor.visitMethodInsn( INVOKESTATIC,
                                       POINTER_TYPE,
                                       "getAddress",
                                       "(L" + POINTER_TYPE + ";)J" );

        if ( getNativeType() == 'I' )
        {
            methodVisitor.visitInsn( L2I );
        }
    }

    /** {@inheritDoc} */
    @Override
    void writeReturnParameter( final MethodVisitor methodVisitor,
                               final int returnVarIndex )
    {
        if ( getNativeType() == 'I' )
        {
            methodVisitor.visitVarInsn( ILOAD, returnVarIndex );
            methodVisitor.visitMethodInsn( INVOKESTATIC,
                                           POINTER_TYPE,
                                           "fromAddress",
                                           "(I)L" + DniTypes.POINTER_TYPE + ";" );
        }
        else
        {
            assert getNativeType() == 'J';

            methodVisitor.visitVarInsn( LLOAD, returnVarIndex );
            methodVisitor.visitMethodInsn( INVOKESTATIC,
                                           POINTER_TYPE,
                                           "fromAddress",
                                           "(J)L" + DniTypes.POINTER_TYPE + ";" );
        }
        methodVisitor.visitInsn( ARETURN );
    }

}
